define(['config', 'text!app/module/system/user.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {

    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/user/list";
    //console.log(token);

    var model = avalon.define({
        $id: "users",
        userInfo: {},
        query: {
            keyword: "",
            start_date: "",
            end_date: "",
            status: ""
        },
        roleList: [],
        onInit: function () {
            avalon.log('ok');
        },
        init: function () {
            model.loadGrid();
            model.addEvent();
        },
        loadGrid: function () {
            avalon.log(model.query);

            function t(val, opt, row) {
                var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="javascript:void();" ms-click="edit(el)"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
                return html_con;
            }
            var i = Public.setGrid();
            $("#grid").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                datatype: "json",
                mtype: "POST",
                url: 　grid_url,
                postData: model.query.$model,
                autowidth: true,
                height: i.h,
                altRows: true,
                gridview: true,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                loadComplete: function (data) {
                    avalon.log("data" + data);
                },
                loadError: function (xhr, status, error) {
                    avalon.log(xhr);
                    avalon.log(status);
                    avalon.log(error);
                    alert(JSON.parse(xhr.responseText).msg);
                },
                colModel: [{
                        name: "operating",
                        label: "操作",
                        fixed: true,
                        width: 100,
                        formatter: t,
                        align: "center",
                        title: false
                    },
                    {
                        name: "id",
                        label: "ID",
                        align: "center",
                        width: 100,
                        title: false
                    },
                    {
                        name: "userName",
                        label: "用户名",
                        align: "center",
                        width: 100,
                        title: false
                    },
                    {
                        name: "email",
                        label: "邮箱",
                        align: "center",
                        width: 100,
                        title: false
                    },
                    {
                        name: "employeeId",
                        label: "员工",
                        align: "center",
                        width: 100,
                        title: false
                    },
                    {
                        name: "status",
                        label: "状态",
                        align: "center",
                        width: 100,
                        title: false
                    }, {
                        name: "roles",
                        label: "角色",
                        align: "center",
                        formatter: function (val) {
                            if (val.length > 0) {
                                var role = "";
                                for (i = 0; i < val.length; i++) {
                                    role += val[i]["description"] + ",";
                                }
                                return role.substr(0, role.length - 1);
                            }
                            return "";
                        },
                        width: 100,
                        title: false
                    },
                    {
                        name: "creater_name",
                        label: "创建人",
                        align: "center",
                        width: 100,
                        title: false
                    },
                    {
                        name: "create_datetime",
                        label: "创建时间",
                        align: "center",
                        width: 100,
                        title: false
                    }, {
                        name: "rolemanage",
                        label: "角色管理",
                        align: "center",
                        formatter: function () {
                            return "<a class='roleManage' href='javascript:void(0)'><span>设置角色</span></a>"
                        }
                    }
                ],
                cmTemplate: {
                    sortable: false,
                    title: false
                },
                page: 1,
                sortname: "id",
                sortorder: "desc",
                pager: "#page",
                rowNum: 10,
                rowList: [10, 20, 50],
                viewrecords: true,
                shrinkToFit: false,
                forceFit: false,
                jsonReader: {
                    root: "data.list",
                    records: "data.totalRow",
                    total: "data.totalPage",
                    repeatitems: false,
                    id: "id"
                },
                loadError: function () {
                    parent.Public.tips({
                        type: 1,
                        content: "加载数据异常！"
                    })
                },
                ondblClickRow: function (t) {
                    model.view(t);
                }
            })
        },
        reset: function () {
            model.query = {
                keyword: "",
                start_date: "",
                end_date: "",
                status: ""
            };
            model.reloadData();
        },
        reloadData: function () {
            $("#grid").jqGrid("setGridParam", {
                url: grid_url,
                datatype: "json",
                mtype: 'POST',
                postData: model.query.$model
            }).trigger("reloadGrid");
        },
        edit: function (userInfo) {
            if (userInfo === -1) { // 创建用户
                model.userInfo = {};
                url = "/api/user/newUser";
            } else { // 修改用户
                model.userInfo = userInfo;
                url = "/api/user/updUser";
            }
            // 弹出层
            dialog({
                title: '编辑用户信息',
                content: $('#editUser'),
                okValue: "确定",
                ok: function () {
                    // 提交修改
                    $.ajax({
                        type: "POST",
                        url: url,
//						dataType: 'json',
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(model.userInfo),
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        success: function (data, status, xhr) {
                        	model.reset();
                            avalon.log(data);
                        },
                        error: function (responseData, textStatus, errorThrown) {
                            alert("Failed: " + responseData);
//                            alert("Failed: " + testStatus);
//                            alert("Failed: " + errorThrown);
                        }

                    });
//                    $.post(url, $("#userForm").serialize());
                },
                cancelValue: "取消",
                cancel: function () {}
            }).showModal();
        },
        setRole: function (id) {
            var urs = [];
            $.ajax({
                url: "/api/role/getAll",
                headers: {
                    "X-AuthToken": token
                },
                success: function (data) {
                    model.roleList = data.data;
                    $("#setRole").each(function () {
                        for (var i = 0; i < data.data.length; i++) {
                            if (data.data[i] = $(this).text()) {
                                $(this).attr("checked", "checked");
                            }
                        }
                    })
                }
            })
            dialog({
                title: "修改用户角色",
                content: $("#setRole"),
                okValue: "确定",
                ok: function () {
                    $("input[type='checkbox']:checked").each(function () {
                        urs.push(parseInt($(this).text()));
                    });
                    // 提交修改
                    $.post("admin/role/setRole", {
                        ids: urs
                    });
                },
                cancelValue: "取消",
                cancel: function () {}
            }).showModal();
        },
        del: function (ids) {
            dialog({
                title: "确认操作",
                content: "确定删除？ 此操作不可恢复！",
                okValue: "确定",
                ok: function () {

                    $.ajax({
                        type: "POST",
                        url: "api/user/delUser",
                        data: {
                            "ids": ids
                        },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        success: function (data, status, xhr) {
                            if (data) {
                                $('#grid').jqGrid('delRowData', ids);
                            }
                        },
                        error: function (responseData, textStatus, errorThrown) {
                            alert("Failed: " + responseData);
                        }

                    });

                },
                cancelValue: "取消",
                cancel: function () {}
            }).showModal();
        },
        addEvent: function () {
            var t = this;
            $(".grid-wrap").on("click", ".fa-edit", function (e) {
                var t = $(this).parent().data("id");
                model.edit($("#grid").getRowData(t));
            });
            $(".grid-wrap").on("click", ".roleManage", function (e) {
                var t = $(this).parent().data("id");
                var url = "/api/role/getAll";
                var func = function (data) {
                    console.log(data);
                }
                Public.ajaxGet(url, null, token, func);
                model.setRole($("#grid").getRowData(t));
            });
            // 删除
            $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                var ei = [];
                var e = $(this).parent().data("id");
                ei.push(e);
                model.del(e);
            });
            $("#search").click(function (e) {
                e.preventDefault();
                model.reloadData();
            });
            $(".fa-refresh").click(function (e) {
                e.preventDefault();
                model.reset();
                model.reloadData();
            })
            $("#add").click(function (t) {
                model.edit(-1);
            });
            $("#btn-batchDel").click(function (e) {
                e.preventDefault();
                //if (Business.verifyRight("BU_DELETE")) {
                var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                t.length ? model.del(t.join()) : parent.Public.tips({
                    type: 2,
                    content: "请选择需要删除的项"
                })
                //}
            });
            // 设置用户角色
            $("#setRole").click(function (t) {
                model.setRole();
            });
        }
    });

    require(['jquery', 'domReady!'], function ($) {});

    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});